/*
 DNN Content Builder - sourceforge.net/projects/dnncb
 Copyright (c) 2004-2008
 by Emerson Lopes (emersonlopes@gmail.com)

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.
*/

// DotNetNuke Visual C# source code for Generic Data Provider base class, generated sexta-feira, 8 de outubro de 2004 at 21:30:44
// Generated by DotNetNuke DAL Builder 2 from www.dotnetnuke.dk version 2.1.1714.41920

using System;
using System.Data;
using System.Reflection;
using System.Data.SqlClient;

namespace DNNContentBuilder 
{
    
	public abstract class DataProvider 
	{
		private ConnectionProvider connectionProvider = null;

		// Provider constants - eliminates need for Reflection later
		private const string dataProviderType = "data";
		private const string dataNameSpace = "DNNContentBuilder";
		private const string dataAssemblyName = "DNNContentBuilder";
		
		public static DataProvider Instance()
		{
			return DataProvider.Instance(null);
		}

		public static DataProvider Instance(ConnectionProvider cp) 
		{
			string strCacheKey = dataNameSpace + "." + dataProviderType + "provider";
            
			// Use the cache because the reflection used later is expensive
			ConstructorInfo constructor = (ConstructorInfo)DotNetNuke.Common.Utilities.DataCache.GetCache(strCacheKey);

			if (constructor == null) 
			{
				DotNetNuke.Framework.Providers.ProviderConfiguration providerConfiguration = DotNetNuke.Framework.Providers.ProviderConfiguration.GetProviderConfiguration(dataProviderType);
				string strTypeName = null;

				try 
				{
					// Override the typename if a ProviderName is specified ( this allows the application to load a different DataProvider assembly for custom modules)
					strTypeName = dataNameSpace + "." + providerConfiguration.DefaultProvider + ", " + dataAssemblyName + "." + providerConfiguration.DefaultProvider;
					// Use reflection to store the constructor of the class that implements DataProvider
					Type t = Type.GetType(strTypeName, true);
					constructor = t.GetConstructor(System.Type.EmptyTypes);
					// Insert the type into the cache
					DotNetNuke.Common.Utilities.DataCache.SetCache(strCacheKey, constructor);
				} 
				catch (Exception e) 
				{
					throw new ApplicationException("Could not load data provider "+ strTypeName,e);
				}
			}

			DataProvider instance = (DataProvider)constructor.Invoke(null);

			if (instance == null)
			{
				throw new ApplicationException("Could not instantiate specified data provider");
			}

			if (cp == null)
			{
				cp = new ConnectionProvider();
			}

			instance.ConnectionProvider = cp;

			return instance;
		}

		protected ConnectionProvider ConnectionProvider
		{
			get
			{
				return connectionProvider;
			}
			set
			{
				connectionProvider = value;
			}
		}
        
		// Prototype method descriptions

		public abstract IDataReader DatabaseGetAllDatabases();
		public abstract IDataReader DatabaseGet(Int32 databaseId);

		public abstract Int32 ConnectionStringAdd(string title, Int32 databaseId, string connectionString);
		public abstract void ConnectionStringUpdate(Int32 connectionStringId, string title, Int32 databaseId, string connectionString);
		public abstract void ConnectionStringDelete(Int32 connectionStringId);
		public abstract IDataReader ConnectionStringGet(Int32 connectionStringId);
		public abstract IDataReader ConnectionStringGetByTitle(string connectionTitle);
		public abstract IDataReader ConnectionStringGetAllConnections();
        
		public abstract Int32 ContentManagerSettingsAdd(Int32 formDefinitionId, Int32 workflowId, Int32 moduleID);
		public abstract void ContentManagerSettingsUpdate(Int32 contentManagerSettingsId, Int32 formDefinitionId, Int32 workflowId, Int32 moduleID);
		public abstract void ContentManagerSettingsDelete(Int32 contentManagerSettingsId);
		public abstract IDataReader ContentManagerSettingsGet(Int32 contentManagerSettingsId);
		public abstract IDataReader ContentManagerSettingsByFormDefinition(Int32 formDefinitionId);
		public abstract IDataReader ContentManagerSettingsByWorkflow(Int32 workflowId);
		public abstract IDataReader ContentManagerSettingsByModules(Int32 moduleID);
        
		public abstract Int32 ContentSecurityAdd(Int32 metaDataId, string contentAuthorizedViewer);
		public abstract void ContentSecurityUpdate(Int32 contentSecurityId, Int32 metaDataId, string contentAuthorizedViewer);
		public abstract void ContentSecurityDelete(Int32 contentSecurityId);
		public abstract IDataReader ContentSecurityGet(Int32 contentSecurityId);
		public abstract IDataReader ContentSecurityByMetaData(Int32 metaDataId);
        
		public abstract Int32 ContentViewerSettingsAdd(Int32 moduleID, Int32 templateDefinitionId);
		public abstract void ContentViewerSettingsUpdate(Int32 contentViewerSettingsId, Int32 moduleID, Int32 templateDefinitionId);
		public abstract void ContentViewerSettingsDelete(Int32 contentViewerSettingsId);
		public abstract IDataReader ContentViewerSettingsGet(Int32 contentViewerSettingsId);
		public abstract IDataReader ContentViewerSettingsByTemplateDefinition(Int32 templateDefinitionId);
		public abstract IDataReader ContentViewerSettingsByModules(Int32 moduleID);
        
		public abstract Int32 LabelAdd(string shortName, Int32 moduleId);
		public abstract void LabelUpdate(Int32 labelId, string shortName, Int32 moduleId);
		public abstract void LabelDelete(Int32 labelId);
		public abstract IDataReader LabelGet(Int32 labelId);
		public abstract IDataReader LabelGetAll();
		public abstract IDataReader LabelGetByModule(Int32 moduleId);

		public abstract Int32 MetaDataLabelAdd(Int32 metaDataId, Int32 labelId);
		public abstract void MetaDataLabelDelete(Int32 metaDataId, Int32 labelId);
		public abstract void MetaDataLabelDeleteByLabel(Int32 labelId);

		public abstract Int32 ControlTypeAdd(string title, string controlPath, string typeName, string assemblyName, string nameSpace);
		public abstract void ControlTypeUpdate(Int32 controlTypeId, string title, string controlPath, string typeName, string assemblyName, string nameSpace);
		public abstract void ControlTypeDelete(Int32 controlTypeId);
		public abstract IDataReader ControlTypeGet(Int32 controlTypeId);
		public abstract IDataReader ControlTypeGetItemByPath(string path);
		public abstract IDataReader ControlTypeGetAllControlType();
        
		public abstract void DataConnectionAdd(string tableName, Int32 connectionStringId, string primaryKeyName);
		public abstract void DataConnectionUpdate(Int32 dataConnectionId, string tableName, Int32 connectionStringId, string primaryKeyName);
		public abstract void DataConnectionDelete(Int32 dataConnectionId);
		public abstract IDataReader DataConnectionGet(Int32 dataConnectionId);
		public abstract IDataReader DataConnectionByConnectionString(Int32 connectionStringId);
		public abstract IDataReader DataConnectionGetAllDataConnections();
		public abstract IDataReader DataConnectionGetByTableName(string tableName);
        
		public abstract Int32 FieldDefinitionAdd(string title, string cssClass, bool search, string tooltip, bool required, string sourceField, Int32 formDefinitionId, Int32 controlTypeId, int tabIndex, string XML, bool visible, bool isTitle, Int32 dataConnectionId);
		public abstract void FieldDefinitionUpdate(Int32 fieldDefinitionId, string title, string cssClass, bool search, string tooltip, bool required, string sourceField, Int32 formDefinitionId, Int32 controlTypeId, string XML, bool visible, bool isTitle, Int32 dataConnectionId);
		public abstract void FieldDefinitionDelete(Int32 fieldDefinitionId);
		public abstract void FieldDefinitionDeleteAllFieldDefinitions(Int32 formDefinitionId);
		public abstract IDataReader FieldDefinitionGet(Int32 fieldDefinitionId);
		public abstract IDataReader FieldDefinitionByControlType(Int32 controlTypeId);
		public abstract IDataReader FieldDefinitionByFormDefinition(Int32 formDefinitionId);
		public abstract IDataReader FieldDefinitionGetFieldDefinitionControlTypes(Int32 formDefinitionId);
        
		public abstract void FormDataConnectionsAdd(Int32 formDefinitionId, Int32 dataConnectionId);
		public abstract void FormDataConnectionsUpdate(Int32 formDefinitionId, Int32 dataConnectionId);
		public abstract void FormDataConnectionsDeleteByFormDefinition(Int32 formDefinitionId);
		public abstract void FormDataConnectionsDelete(Int32 formDefinitionId, Int32 dataConnectionId);
		public abstract IDataReader FormDataConnectionsGet(Int32 formDefinitionId, Int32 dataConnectionId);
		public abstract IDataReader FormDataConnectionsByDataConnection(Int32 dataConnectionId);
		public abstract IDataReader FormDataConnectionsByFormDefinition(Int32 formDefinitionId);
        
		public abstract Int32 FormDefinitionAdd(string title, string css);
		public abstract void FormDefinitionUpdate(Int32 formDefinitionId, string title, string css);
		public abstract void FormDefinitionDelete(Int32 formDefinitionId);
		public abstract IDataReader FormDefinitionGet(Int32 formDefinitionId);
		public abstract IDataReader FormDefinitionGetByTitle(string formTitle);
		public abstract IDataReader FormDefinitionGetAllFormDefinition();
		public abstract IDataReader FormDefinitionGetFormDefinitionDataConnections();
		public abstract IDataReader FormDefinitionGetFormDefinitionFieldDefinition();
        
		public abstract Int32 MetaDataAdd(string title, string pkValue, string status, Int32 taxonomyId, Int32 formDefinitionId, DateTime scheduleDate, Int32 dataConnectionId, Int32 userID, Int32 portalID, DateTime publishDate, DateTime expireDate, DateTime creationDate);
		public abstract void MetaDataUpdate(Int32 metaDataId, string title, string pkValue, string status, Int32 taxonomyId, Int32 formDefinitionId, DateTime scheduleDate, DateTime CreationDate, Int32 dataConnectionId, Int32 userID, Int32 portalID, DateTime publishDate, DateTime expireDate);
		public abstract void MetaDataDelete(Int32 metaDataId);
		public abstract void MetaDataDeleteSchedule(Int32 metaDataId);
		public abstract IDataReader MetaDataGet(Int32 metaDataId);
		
		//CMS related 
		public abstract IDataReader MetaDataGetAddingHit(string guid, string userRoles);
		public abstract IDataReader MetaDataByPKValue(string pkValue, string userRoles);
		public abstract IDataReader MetaDataByFormDefinition(Int32 portalId, Int32 formId, Int32 rowCount, string where, string orderBy, string userRoles);
		//Done
		public abstract IDataReader MetaDataByTaxonomy(Int32 portalId, Int32 formId, Int32 taxonomyId, Int32 rowCount, string where, string orderBy, string userRoles);
		//Done
		public abstract IDataReader MetaDataXRefByTaxonomy(Int32 portalId, Int32 formId, Int32 taxonomyId, Int32 rowCount, string where, string orderBy, string userRoles);
		//Done
		public abstract IDataReader MetaDataByPortal(Int32 portalID);
		//Done
		public abstract IDataReader MetaDataByUser(Int32 userID);
		//Done
		public abstract IDataReader MetaDataGetAllMetaData(Int32 PortalID);
		//Done
		public abstract IDataReader MetaDataGetMetaDataByUser(Int32 PortalID, Int32 UserID);
		//Done
		public abstract IDataReader MetaDataGetMoreRecentApprovedContent(Int32 portalId, Int32 formId, string userRoles);
		
		public abstract IDataReader MetaDataGetMostPopularItems(Int32 portalId, Int32 formId, Int32 rowCount, bool onlyPublished, string userRoles);
		//Done
		public abstract IDataReader MetaDataGetScheduledContent(Int32 PortalID, Int32 ModuleID);
		//Done
		public abstract IDataReader MetaDataPublishScheduledContent(Int32 PortalID);
		//Done
		public abstract IDataReader MetaDataGetNotApprovedMetaDataByUser(Int32 PortalID, DateTime PublishDate, Int32 UserID);
		//Done
		public abstract IDataReader MetaDataGetWorkingMetaDataByUser(Int32 PortalID, Int32 UserID);
        
		public abstract Int32 MetaDataTaskAdd(Int32 taskOrder, DateTime startDate, string status, string title, DateTime finishDate, Int32 metaDataId);
		public abstract void MetaDataTaskUpdate(Int32 metaDataTaskId, Int32 taskOrder, DateTime startDate, string status, string title, DateTime finishDate, Int32 metaDataId);
		public abstract void MetaDataTaskDelete(Int32 metaDataTaskId);
		public abstract void MetaDataTaskDeleteAll(Int32 metaDataId);

		public abstract IDataReader MetaDataTaskGet(Int32 metaDataTaskId);
		public abstract IDataReader MetaDataTaskByTaskOwner(Int32 taskOwnerId);
		public abstract IDataReader MetaDataTaskGetMetaDataTasksByOwner(Int32 TaskOwnerId);
		public abstract IDataReader MetaDataTaskGetMetaDataTasksByOwnerAndModule(Int32 taskOwnerId, Int32 moduleId); 
		public abstract IDataReader MetaDataTaskGetNext(Int32 metaDataId, Int32 taskOrder);
		public abstract IDataReader MetaDataTaskGetCurrent(Int32 metaDataId);

		public abstract Int32 MetaDataTaskOwnerAdd(Int32 OwnerId, string OwnerType, Int32 MetaDataTaskId);
		public abstract void MetaDataTaskOwnerUpdate(Int32 MetaDataTaskOwnerId, Int32 OwnerId, string OwnerType, Int32 MetaDataTaskId);
		public abstract void MetaDataTaskOwnerDeleteAll(Int32 metaDataTaskOwnerId);
		public abstract void MetaDataTaskOwnerDelete(Int32 metaDataTaskOwnerId);
		public abstract IDataReader MetaDataTaskOwnerGet(Int32 metaDataTaskOwnerId);
		public abstract IDataReader MetaDataTaskOwnerGetNext(Int32 metaDataTaskId);

		// Metadata Events
		public abstract Int32 MetaDataEventAdd(Int32 metadataId, string eventType, string eventDescription, string eventDetails, int userId, DateTime eventDate);
		public abstract IDataReader MetaDataEventGet(Int32 eventId);
		public abstract IDataReader MetaDataEventGetAll();
		public abstract IDataReader MetaDataEventGetByMetaDataId(Int32 metaDataTaskId);

	
		//TASKOWNER (running tasks)
		public abstract Int32 TaskOwnerAdd(Int32 ownerId, string ownerType, Int32 taskId);
		public abstract void TaskOwnerUpdate(Int32 taskOwnerId, Int32 ownerId, string ownerType, Int32 taskId);
		public abstract void TaskOwnerDelete(Int32 taskOwnerId);
		public abstract IDataReader TaskOwnerGet(Int32 taskOwnerId);
		public abstract IDataReader TaskOwnerGetTasksByOwner(Int32 OwnerId);
		public abstract IDataReader TaskOwnerGetTaskOwners(Int32 taskId);
		
		//TASKS (model tasks)
		public abstract Int32 TasksAdd(string title, string description, Int32 workflowId, Int32 taskOrder);
		public abstract void TasksUpdate(Int32 taskId, string title, string description, Int32 workflowId, Int32 taskOrder);
		public abstract void TasksDelete(Int32 taskId);
		public abstract void DeleteWorkflowTasks(Int32 workflowId);
		public abstract IDataReader TasksGet(Int32 taskId);
		public abstract IDataReader TasksByWorkflow(Int32 workflowId);
		public abstract IDataReader TasksGetTasksByWorkflow(Int32 WorkflowId);
		
		
		public abstract Int32 TaxonomyAdd(string title, string description, Int32 parentId);
		public abstract void TaxonomyUpdate(Int32 taxonomyId, string title, string description, Int32 parentId);
		public abstract void TaxonomyDelete(Int32 taxonomyId);
		public abstract IDataReader TaxonomyGet(Int32 taxonomyId);
		public abstract IDataReader TaxonomyByTitle(string taxonomyTitle, Int32 parentId);
		public abstract IDataReader TaxonomyGetTaxonomyRoot();
		public abstract IDataReader TaxonomyGetTaxonomySubTree(Int32 ParentId);
        
		public abstract Int32 TemplateDefinitionAdd(string templateName, string body, Int32 formDefinitionId);
		public abstract void TemplateDefinitionUpdate(Int32 templateDefinitionId, string templateName, string body, Int32 formDefinitionId);
		public abstract void TemplateDefinitionDelete(Int32 templateDefinitionId);
		public abstract IDataReader TemplateDefinitionGet(Int32 templateDefinitionId);
		public abstract IDataReader TemplateDefinitionGetByName(string templateName);
		public abstract IDataReader TemplateDefinitionByModuleId(Int32 moduleId);
		public abstract IDataReader TemplateDefinitionGetByFormId(Int32 FormDefinitionId);
        
		public abstract Int32 WorkflowAdd(string title, string description);
		public abstract void WorkflowUpdate(Int32 workflowId, string title, string description);
		public abstract void WorkflowDelete(Int32 workflowId);
		public abstract IDataReader WorkflowGet(Int32 workflowId);
		public abstract IDataReader WorkflowGetAllWorkflows();
	}
	
	public class ConnectionProvider : System.IDisposable
	{
		#region Member Variables
		private const string providerType = "data";

		private DotNetNuke.Framework.Providers.ProviderConfiguration providerConfiguration = DotNetNuke.Framework.Providers.ProviderConfiguration.GetProviderConfiguration(providerType);

		private IDbConnection connection = null;
		private IDbTransaction transaction = null;
		private string connectionString = null;
		private bool disposed = false;
		#endregion

		#region Constructors
		public ConnectionProvider ()
		{
		}
		#endregion

		#region Finalizer
		~ConnectionProvider () 
		{
			Dispose(false);
		}
		#endregion

		#region Properties
		public string ConnectionString
		{
			get
			{
				if (connectionString == null)
				{
					DotNetNuke.Framework.Providers.Provider provider = (DotNetNuke.Framework.Providers.Provider)providerConfiguration.Providers[providerConfiguration.DefaultProvider];
					connectionString = System.Configuration.ConfigurationSettings.AppSettings[provider.Attributes["connectionStringName"]]; 
				}

				return connectionString;
			}
		}

		public IDbTransaction DBTransaction
		{
			get
			{
				return this.transaction;
			}
		}

		public IDbConnection DBConnection
		{
			get
			{
				return this.connection;
			}
		}
		#endregion

		#region Implementation
		public void OpenConnection()
		{
			if (connection == null)
			{
				connection = this.CreateConnection();
			}

			if (connection.State != ConnectionState.Open)
			{
				connection.Open();
			}
		}

		public void CloseConnection()
		{
			if (connection != null && connection.State != ConnectionState.Closed)
			{
				connection.Close();
			}
		}

		public void BeginTransaction() 
		{
			this.BeginTransaction(IsolationLevel.Serializable);
		}

		public void BeginTransaction(IsolationLevel isolationLevel)
		{
			if (connection == null)
			{
				this.OpenConnection();
			}

			this.transaction = connection.BeginTransaction(isolationLevel);
		}

		public void Commit()
		{
			if (transaction != null)
			{
				transaction.Commit();
			}
		}

		/// <summary>
		/// Rolls back a transaction from a pending state.
		/// </summary>
		public void Rollback()
		{
			if (transaction != null)
			{
				transaction.Rollback();
			}
		}
		#endregion

		#region Protected Members
		protected virtual IDbConnection CreateConnection()
		{
			return new SqlConnection(this.ConnectionString);
		}
		#endregion

		#region IDisposable Members

		void IDisposable.Dispose()
		{
			if (!disposed) 
			{
				Dispose(true);
			}
		}

		protected void Dispose(bool isDisposing) 
		{
			if (isDisposing) 
			{
				GC.SuppressFinalize(this);
			}
			
			if (this.transaction != null)
			{
				this.transaction.Dispose();
			}

			if (this.connection != null) 
			{
				this.connection.Dispose();
			}
		}
		#endregion
	}
}
